package com.shemy.controller;

import com.shemy.entity.SysMenu;
import com.shemy.entity.SysRole;
import com.shemy.entity.SysUser;
import com.shemy.service.SysMenuService;
import com.shemy.service.SysRoleService;
import com.shemy.service.SysUserService;
import com.shemy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description
 * @Author Dzsom
 * @Date 2019-05-07 15:46
 * @Encoding UTF-8
 * @Version 1.0
 **/
@Controller
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("/login")
    public ModelAndView loginPage(){
        return new ModelAndView("login");
    }

    @GetMapping("/index")
    public ModelAndView indexPage(){
        return new ModelAndView("index");
    }

    @GetMapping("/unauthorized")
    public ModelAndView unauthorized(){
        return new ModelAndView("unauthorized");
    }

    @PostMapping("/login")
    public ModelAndView login(HttpSession session,String username,String password){
        ModelAndView modelAndView = new ModelAndView();
        List<SysUser> users = sysUserService.login(username, password);
        if (users.size()==1){
            session.setAttribute("username", username);
            Integer userId = users.get(0).getUserId();
            List<SysRole> sysRoles = sysRoleService.findAllByUserId(userId);
            List<SysMenu> sysMenus = sysMenuService.findAllByRoles(sysRoles);
            modelAndView.setViewName("redirect:index");
            session.setAttribute("menus", sysMenus);
            session.setAttribute("roles", sysRoles);
        }else {
            modelAndView.setViewName("login");
            modelAndView.addObject("error","用户名或密码错误！");
        }
        return modelAndView;
    }
}
